import { Inject, Injectable } from '@nestjs/common'
import { NOTIFY_CLIENT_OPTIONS } from './notify-client.constants'
import { NotifyClientModuleOptions } from './interfaces/notify-client-options.interface'
import fetch from 'node-fetch'
import { NotifyMessageDto } from './dto/notify-message.dto'
import { ResponseDto } from '@boticord/response-serializer'

@Injectable()
export class NotifyClientService {
  constructor(
    @Inject(NOTIFY_CLIENT_OPTIONS) private readonly options: NotifyClientModuleOptions,
  ) {}

  // forcefully disconnects every connection affected by this id
  async forceDisconnect(id: string) {
    const resp = await fetch(`http://notifications-service:${process.env.APP_PORT}/rpc/disconnect/`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Boticord-Rpc': this.options.rpcSecret,
      },
      body: JSON.stringify({ id }),
    })

    return resp.json()
  }

  async broadcastMessage(message: NotifyMessageDto): Promise<ResponseDto<any>> {
    const resp = await fetch(`http://notifications-service:${process.env.APP_PORT}/rpc/publish/`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Boticord-Rpc': this.options.rpcSecret,
      },
      body: JSON.stringify(message),
    })

    return resp.json()
  }
}
